<template>
  <div class="echart-container">
    <div style="position: relative; width: 100%; height: 100%;">
      <slot></slot>
      <div ref="chartRef" style="width: 100%; height: 100%;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useEcharts } from "@/hooks/useEcharts.js"

const props = defineProps({
  options: {
    type: Object,
    required: true
  },
  mapData: {
    type: Object,
    required: false
  },
  backgroundColor: {
    type: String,
    default: '#fff' // 默认白色背景
  }
})

const chartRef = ref(null)
const { initChart, setOptions, getEchartsInstance, disposeChart } = useEcharts()

let chartInstance = null

onMounted(() => {
  nextTick(() => {
    if (chartRef.value) {
      chartInstance = initChart(chartRef.value, props.options, props.mapData)
    }
  })
})

// 监听 options 变化
watch(
    () => props.options,
    (newOptions) => {
      if (newOptions && chartRef.value) {
        setOptions(chartRef.value, newOptions)
      }
    },
    { deep: true }
)

// 组件卸载时清理资源
onUnmounted(() => {
  if (chartRef.value) {
    disposeChart(chartRef.value)
  }
})

// 暴露方法给父组件
defineExpose({
  getEchartsInstance: () => getEchartsInstance(chartRef.value),
  resize: () => {
    if (chartRef.value) {
      resizeChart(chartRef.value)
    }
  }
})
</script>

<style scoped>
.echart-container {
  width: 100%;
  height: 100%;
  border-radius: 15px;
  overflow: hidden;
  background-color: #1E293B;

}
</style>
